package org.example.blogger.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.example.blogger.constant.Constants;
import org.example.blogger.model.Result;
import org.example.blogger.model.UserInfo;
import org.example.blogger.service.UserService;
import org.example.blogger.utils.JwtUtils;
import org.example.blogger.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    //1.验证用户合法性
    //2.验证账号与密码
    //3.返回token
    @RequestMapping("/login")
    public Result login(String username,String password){
        //输入防止为空
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)){
            return Result.fail("用户名或密码不能为空");
        }

        //根据输入在数据库中查询,并赋值
        UserInfo userInfo = userService.selectByName(username);

        //数据为空,则查询为空,不存在
        if(userInfo == null){
            return Result.fail("用户名不存在");
        }

        //验证密码是否相等
        if (!SecurityUtils.verify(password,userInfo.getPassword())) {
            return Result.fail("密码错误");
        }

        //返回token
        Map<String,Object> claim = new HashMap<>();
        //不安全,不要存入敏感信息
        claim.put(Constants.TOKEN_ID,userInfo.getId());
        claim.put(Constants.TOKEN_USERNAME,userInfo.getUserName());
        String token = JwtUtils.genJwtToken(claim);
        return Result.success(token);
    }
    @RequestMapping("/getUserInfo")
    public UserInfo getLoginUserInfo(HttpServletRequest request){
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        Integer userId  = JwtUtils.getIdByToken(token);
        if (userId == null){
            //用户未登录
            return null;
        }
        UserInfo userInfo = userService.selectById(userId);
        return  userInfo;
    }

    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){
        if (blogId <=0){
            return null;
        }
        UserInfo userInfo = userService.getAuthorInfo(blogId);
        return userInfo;
    }
}
